<?php

App::uses('AppController', 'Controller');

/**
 * Places Controller
 *
 * @property Place $Place
 */
class ImagesController extends AppController {

    private $uploadDir = '';

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->deny('admin_upload', 'admin_uploads');
        $this->uploadDir = WWW_ROOT . 'static' . DS . 'uploads' . DS;
    }

    /**
     * 
     * @return void
     */
    public function admin_upload() {
        Configure::write('debug', 0);
        $this->layout = 'ajax';
        $_FILES['file']['type'] = strtolower($_FILES['file']['type']);
        if ($_FILES['file']['type'] == 'image/png'
                || $_FILES['file']['type'] == 'image/jpg'
                || $_FILES['file']['type'] == 'image/gif'
                || $_FILES['file']['type'] == 'image/jpeg'
                || $_FILES['file']['type'] == 'image/pjpeg') {
            
            App::uses('String', 'Utility');
            $ext = strrchr($_FILES['file']['name'], '.');
            $file = String::uuid();
            $file .= $ext;
            
            $newFilePath = $this->uploadDir . $file;
            
            // copying
            if(!move_uploaded_file($_FILES['file']['tmp_name'], $newFilePath)){
                $this->set("result", json_encode(array('error'=>'Unable to move file: '.$_FILES['file']['tmp_name'].' to destination folder: ' . $newFilePath)));
                return;
            }

            // displaying file
            $array = array(
                'filelink' => '/static/uploads/' . $file
            );
            $this->set("result", stripslashes(json_encode($array)));
        } else {
            $this->set("result", stripslashes(json_encode(array('error'=>'File not valid'))));
        }
    }

    /**
     * @return void
     */
    public function admin_uploads() {
        $files = glob($this->uploadDir.'*');
        $baseUrl = '/static/uploads/';
        $result = array();
        foreach ($files as $file) {
            $f = basename($file);
            $url = $baseUrl . "/$f";
            $result[] = array(
                'thumb' => $url,
                'image' => $url
            );
        }
        $this->set("result", stripslashes(json_encode($result)));
    }

}